const mongoose = require('mongoose');
const Newscate=require('../models/newscate.model');

//新增
exports.addcate=function(req,res,next){
    const newscate = new Newscate(req.body);
    newscate.save().then((data) =>{
        res.json(data);
    });
}
// 查询
exports.getcate=function(req,res,next){
    var type=req.params.type || 2;
    Newscate.find({type:type}).then(data=>{
        var tree=reveseTree(data,null);
        res.json(tree);
    })
} 

function reveseTree (data,pid){
    var result=[],
    temp;
    var data=JSON.parse(JSON.stringify(data));
    for(var i in data){
        if(data[i].parentId==pid){
            result.push(data[i]);
            temp=reveseTree(data,data[i]._id);
            if(temp.length>0){
                data[i].children=temp;
            }
        }
    }
    return result;
}